<?php

namespace App\Http\Controllers\Home;

use App\Models\Post;
use App\Models\PostTopic;
use App\Models\Topic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TopicController extends BaseController
{
    //专题详情页
    public function show(Topic $topic)
    {
        //带文章数的专题
        $topic=Topic::withCount('postTopics')->find($topic->id);
        //专题下面的文章10
        $topicposts=$topic->posts()->orderBy('created_at','desc')->take(10)->get();
        //属于我的文章 但是未投稿
        $myposts=Post::authorBy(\Auth::id())->topicNotBy($topic->id)->get();
        return view('topic.show',compact('topic','topicposts','myposts'));
    }
    //投稿
    public function submit(Topic $topic)
    {
        $this->validate(request(),[
            'post_ids'=>'required|array'
        ]);
        $post_ids=\request('post_ids');
        $topic_id=$topic->id;
        //TODO 此处循环插入 修改一次性插入好一些
        foreach ($post_ids as $post_id){
            PostTopic::firstOrcreate(compact('topic_id','post_id'));
        }

       return back();
    }

}
